//
//  MDHSwiftHeader.swift
//  JSTech
//
//  Created by 高得华 on 2019/5/21.
//  Copyright © 2020 华&梅. All rights reserved.
//

import UIKit

///单例 - 文件配置 类
//let kMMWPTFC = MDHFileConstant.share()

open class MDHSwiftHeader: NSObject {
    
    ///9.0. 普通文本转化成富文本
    ///
    /// - Parameters:
    ///   - colAttr: 富文本显示的颜色
    ///   - title: 总的文本
    ///   - strAttr: 需要转化的富文本
    /// - Returns: 最终的富文本
    @objc class func TranslateToAttributedText(colAttr: UIColor?, title: String, strAttr: [String]) -> NSAttributedString {
        
        let attrString = NSMutableAttributedString.init(string: title)
        if strAttr.count > 0 {
            var color = colAttr
            if color == nil {
                color = kColor_MDH333333()
            }
            for str in strAttr {
                let attrRange = title.range(of: str)
                if attrRange != nil {
                    let from = attrRange?.lowerBound.samePosition(in: title.utf16)
                    let to = attrRange?.upperBound.samePosition(in: title.utf16)
                    let myRange = NSRange(location: title.utf16.distance(from: title.utf16.startIndex, to: from!), length: title.utf16.distance(from: from!, to: to!))
                    attrString.addAttributes([NSAttributedString.Key.foregroundColor : color!], range: myRange)
                }
            }
        }
        return attrString.copy() as! NSAttributedString
    }
    
    ///分界线 创建统一的 分界线 类似登录界面
    @objc public class func createUnifiedViewLine(color: UIColor = kColor_MDHHex("#F4F4F4")) -> UIImageView {
        let viewFJX = UIImageView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.5/kMDHPTAutoScale()))
        viewFJX.backgroundColor = color
        return viewFJX
    }
    
    ///导航栏 字体
    @objc public class func navTitle(title: String = "确定", color: UIColor = kColor_MDH333333(), font: UIFont = UIFont.systemFont(ofSize: 14), left: Bool = true) -> MDHButton {
        return MDHFileConstant.navTitleButton(title, color: color, font: font, left: left, target: nil, action: nil)
    }
    ///导航栏 图片
    @objc public class func navImage(image: String = "", color: UIColor?, left: Bool = true) -> MDHButton {
        return MDHFileConstant.navImageButton(image, color: color, left: left, target: nil, action: nil)
    }
    
    //MARK:- ===== 系统中的 权限管理 监听权限是否已经打开
    ///检测 麦克风 是否开启 ///点击时进行判断语音识别
    @objc public class func checkPrivacyManager(type: BAKit_PrivacyType, block: ((Bool)->())?) -> () {
        let displayName = kMMWPTFC().bundleName
        if type == .messageNotification {
            BAPrivacyManager.shared()?.ba_openMessageNotificationService({ (isOk, type1) in
                if block != nil {
                    block!(isOk)
                }
                if !isOk {
                    AlertViewShowTR("提示", "\(displayName)需要使用消息通知权限,否则无法正常使用APP,是否开启?", "开启", { (index) in
                        if index == 2 {
                            //////"prefs:root=WIFI"
                            GEdwardJTOAPPInter.geShareOpenURL(UIApplication.openSettingsURLString)
                        }
                    })
                }
            })
            return
        }
        if type == .locationServices {
            BAPrivacyManager.shared()?.ba_checkAndRequestPrivacyOfLocationServices({ (status) in
                var isOk = false
                switch status {
                case .authorized, .authorizedWhenInUse, .authorizedAlways:///已经授权过，无需授权
                    isOk = true
                    break
                case .notDetermined:///用户从未进行过授权等处理，首次访问相应内容会提示用户进行授权
                    break
                case .denied:///拒绝
                    AlertViewShowTR("提示", "\(displayName)需要使用定位权限,否则无法正常使用APP,是否开启?", "开启", { (index) in
                        if index == 2 {//////"prefs:root=WIFI"
                            GEdwardJTOAPPInter.geShareOpenURL(UIApplication.openSettingsURLString)
                        }
                    })
                    break
                case .restricted, .notSupport:///应用没有相关权限，且当前用户无法改变这个权限 ///硬件等不支持
                    AlertViewShowOne("对不起,您当前设备不支持使用定位权限~");
                    break
                default:
                    break
                }
                if block != nil {
                    block!(isOk)
                }
            })
            return
        }
        BAPrivacyManager.shared()?.ba_authorizationManagerCheckAccess(for: type, block: { (status, type1) in
            if block != nil {
                block!(status == .authorized)
            }
            var tishi = ""
            switch type1 {
            case .microphone:///麦克风
                tishi = "麦克风"
                break
            case .messageNotification:///消息通知
                tishi = "消息通知"
                break
            case .photos:///相册
                tishi = "相册"
                break
            case .camera:///相机
                tishi = "相机"
                break
            case .speechRecognition:///"语音识别"
                tishi = "语音识别"
                break
            case .mediaAndAppleMusic:///"媒体与 Apple Music"
                tishi = "媒体与Apple Music"
                break
            default:
                break
            }
            //var message = ""
            switch status {
            case .authorized:///已经授权过，无需授权
                break
            case .notDetermined:///用户从未进行过授权等处理，首次访问相应内容会提示用户进行授权
                break
            case .denied:///拒绝
                AlertViewShowTR("提示", "\(displayName)需要使用\(tishi)权限,否则无法正常使用APP,是否开启?", "开启", { (index) in
                    if index == 2 {
                        //////"prefs:root=WIFI"
                        GEdwardJTOAPPInter.geShareOpenURL(UIApplication.openSettingsURLString)
                    }
                })
                //message = "您已拒绝喵喵玩使用麦克风,请到设置-"
                break
            case .restricted, .notSupport:///应用没有相关权限，且当前用户无法改变这个权限 ///硬件等不支持
                AlertViewShowOne("对不起,您当前设备不支持使用\(tishi)权限~");
                //message = "对不起,您当前设备不支持使用麦克风~"
                break
            default:
                break
            }
        })
    }
    
    //MARK: - ==== 第三方库 相关
    ///最顶上的视图 距离顶部的距离的布局
    @objc public class func makeViewNavTopPath(make: MASConstraintMaker?, top: CGFloat = 0) -> () {
        make?.top.equalTo()(top+kMMWPTFC().kNavSafeArea/kMDHPTAutoScale())
    }
    ///距离底部的距离
    @objc public class func makeViewSafeBottomPath(make: MASConstraintMaker?, bottom: CGFloat = 0) -> () {
        make?.bottom.equalTo()(-(bottom+kMMWPTFC().kSafeAreaBottom/kMDHPTAutoScale()))
    }
    
    //MARK: - ==== 点击事件
    ///给视图添加点击事件
    @objc public class func addTap(view: UIView, block: @escaping ((_ tap: UITapGestureRecognizer)->())) -> () {
        if !(view.isUserInteractionEnabled) {
            view.isUserInteractionEnabled = true
        }
        ///弱变量
        weak var weakView = view
        let tap = UITapGestureRecognizer()
        weakView?.addGestureRecognizer(tap)
        tap.rac_gestureSignal()
            .deliverOnMainThread().subscribeNext({ (x) in
                let x_data = x as? UITapGestureRecognizer
                if let x_tap = x_data {
                    block(x_tap)
                }
        })
    }
    
    ///获取截屏图片UIImage对象
    @objc public class func takeSnapshotScreen(view: UIView?) -> UIImage? {
        var image: UIImage?
        if view != nil {
            let isScroll = view?.isKind(of: UIScrollView.classForCoder()) ?? false
            var scrollView: UIScrollView?
            // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，调整清晰度。
            ///区域大小
            var size = view?.bounds.size ?? CGSize.zero
            if isScroll {
                scrollView = (view as? UIScrollView)
                size = scrollView?.contentSize ?? CGSize.zero
            }
            ///是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES
            let opaque = true
            ///屏幕密度了，调整清晰度。
            let scale = UIScreen.main.scale
            UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
            
            ///保存现在的偏移量
            var savedContentOffset = CGPoint.zero
            ///保存现在的位置
            var savedFrame = CGRect.zero
            
            if isScroll {
                ///保存现在的偏移量
                savedContentOffset = scrollView?.contentOffset ?? CGPoint.zero
                ///保存现在的位置
                savedFrame = scrollView?.frame ?? CGRect.zero
                ///
                scrollView?.contentOffset = CGPoint.zero
                scrollView?.frame = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
            }
            
            ///区域
            if let content = UIGraphicsGetCurrentContext() {
                if isScroll {
                    scrollView?.layer.render(in: content)
                }else{
                    view?.layer.render(in: content)
                }
                image = UIGraphicsGetImageFromCurrentImageContext()
                if isScroll {
                    ///设置 原来的偏移量
                    scrollView?.contentOffset = savedContentOffset
                    ///设置 原来的位置
                    scrollView?.frame = savedFrame
                }
                ///绘画 截图 结束
                UIGraphicsEndImageContext()
                if (image != nil) {
                    //保存图片到相册
                    //UIImageWriteToSavedPhotosAlbum(image, <#T##completionTarget: Any?##Any?#>, <#T##completionSelector: Selector?##Selector?#>, <#T##contextInfo: UnsafeMutableRawPointer?##UnsafeMutableRawPointer?#>)
                }
            }
        }
        return image
    }
    
    ///截取长图
    @objc public class func takeSnapshotOfFullContent(scrollView: UIScrollView?) -> UIImage? {
        return MDHSwiftHeader.takeSnapshotScreen(view: scrollView)
    }
    
    //MARK: - ==== 对字符串进行加密
    ///对手机号码进行加密
    @objc public class func encryptionMobilePhoneNumber(mobile: String) -> String {
        if mobile.count < 7 {
            return mobile
        }
        let mp1 = (mobile as NSString).substring(to: 3)
        let mp2 = (mobile as NSString).substring(from: mobile.count-4)
        return mp1+"****"+mp2
    }
    
    ///字符串加密
    @objc public class func encryptionOfStrings(text: String, isPw: Bool = false) -> String {
        return text
        /*var pw = text
        if isPw {
            pw = "data=\(pw)"
        }
        ///随机字符串
        let iv = ("AES-256-CBC" as NSString).randomStr(withLength: 16) ?? ""
        ///私密
        let hexKey = MDHHTTPService.privateKey()
        ///加密
        let result = CocoaSecurity.aesEncrypt(pw, hexKey: hexKey, hexIv: iv)
        ///对参数进行 AES-256-CBC 加密 之后的字符串
        let signedStr = result?.base64 ?? ""
        ///对iv进行 base64 的加密
        let ivJm = (iv as NSString).base64Encoded() ?? ""
        let dict = ["iv": ivJm,
                    "value": signedStr] as NSDictionary
        ///获取最后的json -> 之后 全部 base64 加密
        let sign = ((dict.mj_JSONString() ?? "") as NSString).base64Encoded() ?? ""
        return sign*/
    }
    
    ///复制 文本 - == 传入的文本进行复制
    @objc public class func copyText(text: String, mes: String = "复制成功~") -> () {
        let pasteboard = UIPasteboard.general
        pasteboard.string = text
        ShowHUDMesHidden(mes, nil)
    }
    
    ///通过字符串返回 UIViewController 对象
    @objc class func viewConteoller(name: String, params: [String:String] = [:]) -> UIViewController {
        var vc: UIViewController!
        if name.count > 0 {///swift 视图控制器的前缀
            let ns = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? ""
            let clsName = ns+"."+name
            let ser = MDHRouter.sharedInstance().services
            vc = (NSClassFromString(clsName) as? MDHViewController.Type)?.init(services: ser, params: params)
            if vc == nil {
                vc = (NSClassFromString(name) as? MDHViewController.Type)?.init()
                if vc == nil {
                    vc = (NSClassFromString(clsName) as? UIViewController.Type)?.init()
                    if vc == nil {
                        vc = (NSClassFromString(name) as? UIViewController.Type)?.init()
                    }
                }
            }
        }
        return vc
    }
    
    ///通过字符串返回 MDHViewModel 对象
    @objc class func viewModel(name: String, vs: Int = 0) -> MDHViewModel {
        var vc: MDHViewModel!
        if name.count > 0 {///swift 视图控制器的前缀
            let ns = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? ""
            let clsName = ns+"."+name
            let ser = MDHRouter.sharedInstance().services
            vc = (NSClassFromString(clsName) as? MDHViewModel.Type)?.init(services: ser, params: [MHViewModelIDKey : vs])
            if vc == nil {
                vc = (NSClassFromString(name) as? MDHViewModel.Type)?.init()
            }
        }
        return vc
    }
}


//MARK: - ===== 颜色的扩展 ===== -
extension UIColor {
    ///颜色
    @objc public class func color(hex: String, alpha: CGFloat = 1.0) -> UIColor {
        return UIColor.init(hexStr: hex, alpha: alpha)
    }
}
